layui.use(['form','layer','layedit','laydate','upload'],function(){
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        laydate = layui.laydate,
        $ = layui.jquery;
    //用于同步编辑器内容到textarea
    layedit.sync(editIndex);
    var categoryId = Number($("#category").data("id"));
    renderSelect();

    // 富文本设置上传接口
    upload.render({
        elem: '.thumbBox',
        url: API_BASE_URL+'/article?method=uploadFile',
        method : "post",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
        done: function(res, index, upload){
            layer.msg(res.message)
            $('.thumbImg').attr('src',res.data.src);
            $('.thumbBox').css("background","#fff");
        }
    });
    //格式化时间
    function filterTime(val){
        if(val < 10){
            return "0" + val;
        }else{
            return val;
        }
    }
    //定时发布
    var time = new Date();
    var submitTime = time.getFullYear()+'-'+filterTime(time.getMonth()+1)+'-'+filterTime(time.getDate())+' '+filterTime(time.getHours())+':'+filterTime(time.getMinutes())+':'+filterTime(time.getSeconds());
    laydate.render({
        elem: '#release',
        type: 'datetime',
        trigger : "click",
        done : function(value, date, endDate){
            submitTime = value;
        }
    });
    form.on("radio(release)",function(data){
        if(data.elem.title == "定时发布"){
            $(".releaseDate").removeClass("layui-hide");
            $(".releaseDate #release").attr("lay-verify","required");
        }else{
            $(".releaseDate").addClass("layui-hide");
            $(".releaseDate #release").removeAttr("lay-verify");
            submitTime = time.getFullYear()+'-'+(time.getMonth()+1)+'-'+time.getDate()+' '+time.getHours()+':'+time.getMinutes()+':'+time.getSeconds();
        }
    });

        form.verify({
            newsName : function(val){
                if(val == ''){
                    return "文章标题不能为空";
                }
            },
            // content : function(val){
            //     if(val == ''){
            //         return "文章内容不能为空";
            //     }
            // }
        })
    form.on("submit(addNews)",function(data){
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        // 实际使用时的提交信息
        let params = {
            id: $(".id").val(),
            title : $(".newsName").val(),  //文章标题
            author : $(".author").val(),  //文章作者
            text : layedit.getContent(editIndex).split('<audio controls="controls" style="display: none;"></audio>')[0],  //文章内容
            imgUrl :$(".thumbImg").attr("src"),//缩略图
            isShow : $('.newsStatus').val(),    //发布状态
            textId : $(".textId").val(),
            isDeleted : 0,
            isShow : Number($("#newsStatus").val()),   //是否显示
            categoryName:$('#category').find('option:selected').text(),
            categoryId: Number($("#category").val())
        }
        if ( $(".textId").val()!= ""){

            $.ajax({
                url:API_BASE_URL+'/article?method=update',
                method:"POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                data:JSON.stringify(params),
                success(res){
                    if (res.code == 200){
                        layer.msg(res.message)
                    }
                }
            })
            $(".textId").val(null)
        }
        else {
            $.ajax({
                url: API_BASE_URL + '/article?method=add',
                method: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                data: JSON.stringify(params),
                success(res) {
                    if (res.code == 200) {
                        layer.msg(res.message)
                    }
                    if (res.code == 401){
                        layer.msg(res.message+",2秒后自动跳转登录页")
                        setTimeout(function (){
                            window.location.href = API_BASE_URL+'/admin?method=toLogin'
                        },2000)
                    }
                }
            })
        }
        return false;
    })

    //预览
    form.on("submit(look)",function(){
        let id = $(".id").val();
        window.location.href("/articleDetail.html?id="+id);
        return false;
    })

    //创建一个编辑器
        var editIndex = layedit.build('news_content',{
            height : 535,
            uploadImage: {
                url: API_BASE_URL+'/article?method=uploadFile', //接口url
                type: 'post' //默认post
            }
        });

    function renderSelect(){

        $.ajax({
            url:API_BASE_URL+'/category?method=getCategoryCanUse',
            dataType: 'json',
            type: 'get',
            success: function (data) {
                //使用循环遍历，给下拉列表赋值
                $.each(data.data, function (index, value) {
                    console.log(value.name+''+value.id);
                    $('#category').append(new Option(value.name,value.id));// 下拉菜单里添加元素
                });
                $('#category').val(categoryId);
                layui.form.render("select");//重新渲染 固定写法
            }
        })
    }



})